package com.fubowen.reader.ui.download

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.fubowen.reader.R
import com.fubowen.reader.book.impl.WebBook
import com.fubowen.reader.databinding.FragmentScanWebBinding
import com.fubowen.reader.extension.isUrlToGetBaseUrl
import com.fubowen.reader.extension.setVisible
import com.fubowen.reader.db.model.OptionsMenuItem
import com.fubowen.reader.db.model.Tree
import com.fubowen.reader.ui.fragment.TreeFilterFragment
import com.fubowen.reader.ui.fragment.TreeFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

const val SELECTED_DIALOG_TAG = "SELECTED_DIALOG"
const val FILTER_DIALOG_TAG = "FILTER_DIALOG"
const val COLLECT_DIALOG_TAG = "COLLECT_DIALOG"

class ScanWebFragment : TreeFragment(), IScan {

    private lateinit var binding: FragmentScanWebBinding
    private var collector = lazy { CollectWebSiteFragment() }

    private var filter = lazy { TreeFilterFragment() }

    override val isEnableTree = false
    override var isEnableOptionsMenu = true
    override val button = "打开"
    override var isEnableOnBack = true
    override var optionsMenuList = mutableListOf(OptionsMenuItem(title = "收录网站") { openCollector() })


    //region 重写基类方法
    override fun onItemClick(view: View, item: Tree, position: Int) {
        item.isChecked = !item.isChecked
        if (item.isChecked) cacheViewModel.select(item) else cacheViewModel.delete(item)
        adapter.notifyItemChanged(position)
    }

    override fun onBreadcrumbClick(item: Tree) = submitListToRecyclerView(item)
    override fun onItemButtonClick(view: View, item: Tree, position: Int) = submitListToRecyclerView(item)

    override fun onSizeChanged(size: Int) {
        binding.selected.text = getString(R.string.checkedText, size)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = FragmentScanWebBinding.inflate(inflater)
        super.initRecyclerView(binding.root)
        observerUpdate()
        binding.selected.setOnClickListener { openSelected() }
        binding.filter.setOnClickListener { openFilter() }
        binding.back.setOnClickListener { openCollector() }
        lifecycleScope.launch {
            cacheViewModel.dataSourceFlow.collect {
                adapter.submitList(it)
            }
        }
        return binding.root
    }

    override fun onBack(): Boolean {
        if (super.onBack()) {
            return true
        }
        tree.setVisible(false)
        binding.init.setVisible(true)
        binding.backSelectedFilter.setVisible(false)
        return false
    }

    //endregion

    //region 子类独有方法
    private fun openSelected() = selector.value.show(parentFragmentManager, SELECTED_DIALOG_TAG)

    private fun openFilter() = filter.value.show(parentFragmentManager, FILTER_DIALOG_TAG)

    private fun openCollector() = collector.value.show(parentFragmentManager, COLLECT_DIALOG_TAG)

    private fun observerUpdate() {
        lifecycleScope.launch {
            cacheViewModel.updateFlow.collect { item ->
                val index = adapter.currentList.indexOfFirst { it.absolutePath == item.absolutePath }
                if (index != -1) {
                    adapter.notifyItemChanged(index, item)
                }
            }
        }
    }

    private fun submitListToRecyclerView(item: Tree) {
        if (item.absolutePath.isBlank()) {
            return
        }
        tree.setVisible(true)
        binding.init.setVisible(false)
        binding.backSelectedFilter.setVisible(true)
        showLoading("正在扫描网址...")
        lifecycleScope.launch {
            if (!item.isRead) {
                val webSite = withContext(Dispatchers.IO) { WebBook.webSite(item.absolutePath) }
                if (webSite != null) {
                    database.webSiteDao().setOrIgnore(webSite)
                    item.children += webSite.children
                }
                item.isRead = true
            }
            hideLoading()
            cacheViewModel.submitList(item.children)
        }
        setBreadcrumb(item)
    }

    //endregion

    private fun capture() {
        lifecycleScope.launch {
            val item = adapter.currentList.first()
            val site = item.absolutePath.isUrlToGetBaseUrl()
            withContext(Dispatchers.IO) {
//                val webSite = WebBook.getSiteInfo(site)
//                if (webSite != null) {
//                    database.webSiteDao().set(webSite)
//                }
            }
        }
    }

    override fun scan(url: String) {
        val item = Tree(
            absolutePath = url,
            name = "根路径",
        )
        isEnableOnBack = true
        setOnBack()
        submitListToRecyclerView(item)
    }


}
